package org.example.algorithm.binarytree;

import org.example.algorithm.TreeNode;

public class MaxPathSumSolution {
    private int pathSum = Integer.MIN_VALUE;
    public static void main() {

    }

    public int maxPathSum(TreeNode root) {
        maxSideSum(root);
        return pathSum;
    }

    public int maxSideSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftSideSum = maxSideSum(root.left);
        int rightSideSum = maxSideSum(root.right);
        pathSum = Math.max(pathSum, leftSideSum + rightSideSum + root.val);
        return Math.max(Math.max(leftSideSum, rightSideSum) + root.val, 0);
    }
}
